package com.yangming.common.filter;

import com.alibaba.fastjson.JSON;
import com.yangming.common.base.BaseResponseEnum;
import com.yangming.common.base.Constants;
import com.yangming.common.utils.BackJsonBeanUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author PengShuiMing
 * @create 2018-09-08
 **/
@WebFilter(urlPatterns = "/*", filterName = "OpenIdFilter")
public class OpenIdFilter implements Filter {
    private static final String XML_HTTP_REQUEST = "XMLHttpRequest";
    private static final String X_REQUESTED_WITH = "X-Requested-With";
    @Value("${we.chat.auth.url}")
    private String authUrl;
    /**
     * 不需要用户登录的请求---全部
     */
    private static final String[] WHITE_LIST = {"/public"};
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getServletPath();
        // 1.无需登陆拦截处理
        if (this.excludedPath(url)) {
            filterChain.doFilter(request, response);
            return;
        } else {
            // 2.需登陆拦截处理
            HttpSession session = request.getSession();
            String openId = (String) session.getAttribute(Constants.USER_OPEN_ID_KEY);
            if(StringUtils.isBlank(openId)){
                //提示登录过期需重新登录
                String tip = JSON.toJSONString(BackJsonBeanUtil.getBackJsonBean(BaseResponseEnum.ERROR_NOT_AUTHENTICATION, authUrl));
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(tip);
//                重定向
//                redirectHandler(request,response);
                return;
            }
        }
        filterChain.doFilter(request, response);

    }

    @Override
    public void destroy() {

    }

    /**
     * 不需要过滤的地址
     *
     * @param inputUrl
     * @return
     */
    private boolean excludedPath(String inputUrl) {
        boolean flag = false;
        for (int i = 0; i < WHITE_LIST.length; i++) {
            if (inputUrl.indexOf(WHITE_LIST[i]) >= 0) {
                flag = true;
                break;
            }
        }
        return flag;
    }
    /**
     * 重定向处理器
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void redirectHandler(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 如果request.getHeader("X-Requested-With") 返回的是"XMLHttpRequest"说明就是ajax请求，需要特殊处理
        if (XML_HTTP_REQUEST.equals(request.getHeader(X_REQUESTED_WITH))) {
            // 告诉ajax我是重定向
            response.setHeader("redirect", "redirect");
            // 告诉ajax我重定向的路径
            response.setHeader("contentPath", authUrl);
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        } else {
            // 重定向至登录页
            response.sendRedirect(authUrl);
        }
    }
}
